import 'dart:convert';

import '../../utils/util.dart';
import '../keys.dart';
import '../model/user/user_info.dart';
import 'state.dart';

class UserController {
  final state = UserState();

  static final UserController instance = UserController._interval();
  factory UserController() => instance;
  UserController._interval() {
    init();
  }
  init() {
    initData();
  }

  void initData() async {
    String _token = SpUtil().getStr(key_store_user_token);
    if (_token.isNotEmpty) {
      var _userStr = await SpUtil().getJSON(key_store_user);
      if (_userStr != null) {
        var _userJson = jsonDecode(_userStr);
        configUser(_userJson);
        if (isLogin) {}
      }
    }
  }

  Future<void> loginSuccess(Map<String, dynamic> userJson) async {
    configUser(userJson);
    await save();
  }

  Future<void> loginOutSuccess() async {
    // isLogin = false;

    // EMClient.getInstance.chatManager.fetchHistoryMessages(conversationId)
    isLogin = false;
    state.user?.token = null;

    await SpUtil().remove(key_store_user_token);
  }

  void updateAvater(String avater) {
    if (state.user == null) {
      return;
    }
    // state.user?.updateAvater(avater);
    loginSuccess(state.user!.toJson());
  }

  void configUser(Map<String, dynamic> userJson) {
    isLogin = true;
    state.user = UserInfo.fromJson(userJson);
    state.userObs.value = state.user!;
    state.userObs.refresh();
  }

  final isLoginObs = false.obs;
  set isLogin(bool value) {
    isLoginObs.value = value;
    if (value == false) {
      SpUtil().remove(key_store_user_token);
    }
  }

  bool get isLogin {
    return !isNilStr(state.user?.token);
  }

  final isAtLoginObs = true.obs;
  set isAtLogin(bool value) => isAtLoginObs.value = value;
  bool get isAtLogin => isAtLoginObs.value;

  Future<void> save() async {
    if (state.user != null) {
      var _json = state.user!.toJson();
      await SpUtil().setJSON(key_store_user, jsonEncode(_json));

      await SpUtil().setStr(key_store_user_token, state.user!.token!);
    }
  }
}
